package com.example.music08;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String path = intent.getStringExtra("path");//下载路径
        String file = intent.getStringExtra("file");//保存路径
        InputStream is = null;
        FileOutputStream outputStream = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            if(connection.getResponseCode()==200){
                is = connection.getInputStream();
                outputStream = new FileOutputStream(new File(file));
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len=is.read(bytes))!=-1){
                    outputStream.write(bytes,0,len);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}